﻿

using F29ServerProcess.Interfaces;
using F29ServerProcess.Models;
using IotContract.Dtos.Servers.Process;
using IotContract.Dtos.Servers.Process.F29;
using IotContract.Dtos.Servers.Pushs;
using IotContract.Enums;
using IotContract.Extensions;
using IotContract.Interfaces;
using IotContract.Interfaces.Process;
using IotContract.Models.Process.F29;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using XT.Common.Extensions;
using XT.Common.Services;

namespace _29ServerProcess.DataProcess;
/// <summary>
/// 换盘机调度数据
/// </summary>
public class CebDataProcess : IServerProcessHandle
{
    private readonly IServerMainManager _mainProcess;
    private readonly IProcessDataService _processDataService;
    private readonly ILogService _logService;

    public CebDataProcess(IServerMainManager serverMainManager, IProcessDataService processDataService, ILogService logService)
    {
        _mainProcess = serverMainManager;
        _processDataService = processDataService;
        _logService = logService;
    }
    public string ProcessName { get; set; } = F29ServerConst.ProcessName;
    public IotEquipType ProcessType { get; set; } = IotEquipType.CEB;



    public async Task<bool> ParsingData()
    {
        try
        {
            // 获取数据
            var equips = await _mainProcess.GetEquips<PushSiemensS7Dto>(new IotContract.Models.Clients.ClientRequestCommand
            {
                RequestType = IotEquipType.CEB.ToString(),
                ProtobufType = IotProtobufType.SIEMENS_S7.ToString()
            });


            var cebUnitDic = _processDataService.CebUnits;
            // 拘束机点位不需要设置UnitNum
            Parallel.ForEach(equips, equip =>
            {
                var tags = equip.Tags;
                F29CebUnitDto cebUnit = null;
                if (cebUnitDic.ContainsKey(equip.Num))
                {
                    cebUnit = cebUnitDic[equip.Num];
                }
                else
                {
                    cebUnit = new F29CebUnitDto();
                    cebUnit.EquipNum = equip.Num;
                    cebUnit.EquipId = equip.Id;
                    cebUnit.Connection = equip.Connection;
                    cebUnitDic.TryAdd(equip.Num, cebUnit);
                }
                SetUnitTag(cebUnit, tags);
            });
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

        return true;
    }

    /// <summary>
    /// 取值
    /// </summary>
    /// <param name="scUnit"></param>
    /// <param name="tags"></param>
    private void SetUnitTag(F29CebUnitDto resUnit, List<PushEquipTag> tags)
    {
        resUnit.Tags = tags;
        Parallel.ForEach(resUnit.Tags, tag =>
        {
            int.TryParse(tag.Value, out int result);
            switch (tag.TagProperty)
            {
               
                case "A_MODE":
                    {
                        resUnit.A_Mode = result;
                        break;
                    }
                case "A_CELL_COUNT1":
                    {
                        resUnit.A_Cell_Count1 = result;
                        break;
                    }
                case "A_CELL_COUNT2":
                    {
                        resUnit.A_Cell_Count2 = result;
                        break;
                    }
                case "A_I_CHECK1":
                    {
                        resUnit.A_I_Check1 = result;
                        break;
                    }
                case "A_I_CHECK2":
                    {
                        resUnit.A_I_Check2 = result;
                        break;
                    }
                case "A_I_CHECK3":
                    {
                        resUnit.A_I_Check3 = result;
                        break;
                    }
                case "A_I_CHECK4":
                    {
                        resUnit.A_I_Check4 = result;
                        break;
                    }

                case "A_I_JOB_STATUS":
                    {
                        resUnit.A_I_JobStatus = result;
                        break;
                    }
              
                case "A_TRAY1":
                    {
                        resUnit.A_Tray1 = tag.Value;
                        break;
                    }
                case "A_TRAY2":
                    {
                        resUnit.A_Tray2 = tag.Value;
                        break;
                    }
                case "A_TRAY3":
                    {
                        resUnit.A_Tray3 = tag.Value;
                        break;
                    }
                case "A_TRAY4":
                    {
                        resUnit.A_Tray4 = tag.Value;
                        break;
                    }
                case "A_O_CHECK1":
                    {
                        resUnit.A_O_Check1 = result;
                        break;
                    }
                case "A_O_CHECK2":
                    {
                        resUnit.A_O_Check2 = result;
                        break;
                    }
                case "W_A_O_CHECK1":
                    {
                        resUnit.W_A_O_Check1 = result;
                        break;
                    }
                case "W_A_O_CHECK2":
                    {
                        resUnit.W_A_O_Check2 = result;
                        break;
                    }
                case "W_A_I_CHECK1":
                    {
                        resUnit.W_A_I_Check1 = result;
                        break;
                    }
                case "W_A_I_CHECK2":
                    {
                        resUnit.W_A_I_Check2 = result;
                        break;
                    }
                case "W_A_I_CHECK3":
                    {
                        resUnit.W_A_I_Check3 = result;
                        break;
                    }
                case "W_A_I_CHECK4":
                    {
                        resUnit.W_A_I_Check4 = result;
                        break;
                    }
               


            }
        });
    }

    public async Task<bool> ProcessData()
    {
        var cebUnitDic = _processDataService.CebUnits;
        // 拘束机点位不需要设置UnitNum
        Parallel.ForEach(cebUnitDic.Values, async equip =>
        {

            if (equip.A_Mode == 0)
            {
                equip.IsValidateTray1 = false;              
                equip.IsValidateTray2 = false;
                equip.IsValidateTray3 = false;
                equip.IsValidateTray4 = false;
                equip.HandleTray1 = string.Empty;
                equip.HandleTray2 = string.Empty;
                equip.Message = string.Empty;
                equip.CellInfo1= string.Empty;
                equip.CellInfo2= string.Empty;
                return;
            }
            // 作业托盘1
            if (equip.HandleTray1.IsNullOrEmpty())
            {
                if (equip.A_I_Check3 == 1 && equip.W_A_I_Check3 == 0 && equip.IsValidateTray3 == false)
                {
                    // 验证托盘
                    var result = await _processDataService.ValidateCebEnterTray(new IotContract.Dtos.Remotes.Request.FmsTrayRequest {EquipNum=equip.EquipNum,EmptyTray=equip.A_Tray3 });

                    if (result.Success)
                    {
                        // 验证完成后，确认信号1
                        if(equip.IsValidateTray1 && equip.W_A_I_Check1 == 1)
                        {
                            // 读取托盘电芯
                            var datas = await _processDataService.GetCebChannel(new IotContract.Dtos.Remotes.Request.FmsTrayRequest { EmptyTray = equip.A_Tray3, Tray = equip.A_Tray1, EquipNum = equip.EquipNum });


                            if (datas.Success)
                            {
                                var count = datas.Result.Select(x => x.Results).ChannelToNumber();
                                equip.CellInfo1 = count.Item2;
                                await _processDataService.WriteCeb("A_CELL_COUNT1", count.Item1.ToString(), equip.EquipNum);
                                // 开始进行作业
                                equip.HandleTray1 = equip.A_Tray1;
                            }
                            else
                            {
                                // 写入报错
                                equip.Message = datas.Message;
                                await _processDataService.WriteCeb("W_A_I_CHECK1", "2", equip.EquipNum);
                            }
                        }
                        await _processDataService.WriteCeb("W_A_I_CHECK3", "1", equip.EquipNum);
                    }
                    else
                    {
                        equip.Message = result.Message;
                        await _processDataService.WriteCeb("W_A_I_CHECK3", "2", equip.EquipNum);

                    }
                    equip.IsValidateTray3 = true;


                }
                else if (equip.A_I_Check3 == 0) equip.IsValidateTray3 = false;
                
                if (equip.A_I_Check1==1 && equip.W_A_I_Check1==0 && equip.IsValidateTray1==false)
                {
                    
                    // 验证托盘
                   var validate1= await _processDataService.ValidateCebEnterTray(new IotContract.Dtos.Remotes.Request.FmsTrayRequest {EquipNum=equip.EquipNum,Tray=equip.A_Tray1 });
                  

                    if(validate1.Success)
                    {
                        // 验证完成后，确认信号3
                        if (equip.IsValidateTray3 && equip.W_A_I_Check3 == 1)
                        {
                            // 读取托盘电芯
                            var datas = await _processDataService.GetCebChannel(new IotContract.Dtos.Remotes.Request.FmsTrayRequest { EmptyTray = equip.A_Tray3, Tray = equip.A_Tray1, EquipNum = equip.EquipNum });


                            if (datas.Success)
                            {
                                var count = datas.Result.Select(x => x.Results).ChannelToNumber();
                                equip.CellInfo1 = count.Item2;
                                await _processDataService.WriteCeb("A_CELL_COUNT1", count.Item1.ToString(), equip.EquipNum);
                                // 开始进行作业
                                equip.HandleTray1 = equip.A_Tray1;
                            }
                            else
                            {
                                // 写入报错
                                equip.Message = datas.Message;
                                await _processDataService.WriteCeb("W_A_I_CHECK1", "2", equip.EquipNum);
                            }
                        }
                        await _processDataService.WriteCeb("W_A_I_CHECK1", "1", equip.EquipNum);
                    }
                    else
                    {
                        equip.Message = validate1.Message;
                        await _processDataService.WriteCeb("W_A_I_CHECK1", "2", equip.EquipNum);
                    }
                    equip.IsValidateTray1 = true;
                }            
                else if(equip.A_I_Check1==0) equip.IsValidateTray1 = false;

                
             
            }
            else
            {
                if (equip.A_O_Check1 == 1 && equip.W_A_O_Check1 == 0)
                {


                    // 调用方法通知 两个tray会判断
                   var result= await _processDataService.CebWorkDoneInform(new IotContract.Dtos.Remotes.Request.FmsTrayRequest { EmptyTray=equip.A_Tray3,Tray=equip.A_Tray1,EquipNum=equip.EquipNum });

                    if (result.Success)
                    {
                        await _processDataService.WriteCeb("W_A_O_CHECK1", "1", equip.EquipNum);
                    }
                    else
                    {
                        await _processDataService.WriteCeb("W_A_O_CHECK1", "2", equip.EquipNum);
                    }
                   

                    equip.HandleTray1 = string.Empty;

                }
               
                

            }

            // 作业托盘2
            if (equip.HandleTray2.IsNullOrEmpty())
            {
                if (equip.A_I_Check4 == 1 && equip.W_A_I_Check4 == 0 && equip.IsValidateTray4 == false)
                {
                    // 验证托盘
                    var result = await _processDataService.ValidateCebEnterTray(new IotContract.Dtos.Remotes.Request.FmsTrayRequest { EquipNum = equip.EquipNum, EmptyTray = equip.A_Tray4 });

                    if (result.Success)
                    {
                        // 读取托盘电芯
                        var datas = await _processDataService.GetCebChannel(new IotContract.Dtos.Remotes.Request.FmsTrayRequest { EmptyTray = equip.A_Tray4, Tray = equip.A_Tray2, EquipNum = equip.EquipNum });


                        if (datas.Success)
                        {
                            var count = datas.Result.Select(x => x.Results).ChannelToNumber();
                            equip.CellInfo2 = count.Item2;
                            await _processDataService.WriteCeb("A_CELL_COUNT2", count.Item1.ToString(), equip.EquipNum);
                            // 开始进行作业
                            equip.HandleTray2 = equip.A_Tray2;
                        }
                        else
                        {
                            // 写入报错
                            equip.Message = datas.Message;
                            await _processDataService.WriteCeb("W_A_I_CHECK2", "2", equip.EquipNum);
                        }
                        await _processDataService.WriteCeb("W_A_I_CHECK4", "1", equip.EquipNum);
                    }
                    else
                    {
                        equip.Message = result.Message;
                        await _processDataService.WriteCeb("W_A_I_CHECK4", "2", equip.EquipNum);

                    }
                    equip.IsValidateTray4 = true;


                }
                else if (equip.A_I_Check4 == 0) equip.IsValidateTray4 = false;

                if (equip.A_I_Check2 == 1 && equip.W_A_I_Check2 == 0 && equip.IsValidateTray2 == false)
                {
                    // 验证托盘
                    var validate1 = await _processDataService.ValidateCebEnterTray(new IotContract.Dtos.Remotes.Request.FmsTrayRequest { EquipNum = equip.EquipNum, Tray = equip.A_Tray2 });


                    if (validate1.Success)
                    {
                        // 读取托盘电芯
                        var datas = await _processDataService.GetCebChannel(new IotContract.Dtos.Remotes.Request.FmsTrayRequest { EmptyTray = equip.A_Tray4, Tray = equip.A_Tray2, EquipNum = equip.EquipNum });


                        if (datas.Success)
                        {
                            var count = datas.Result.Select(x => x.Results).ChannelToNumber();
                         
                            equip.CellInfo2 = count.Item2;
                            await _processDataService.WriteCeb("A_CELL_COUNT2", count.Item1.ToString(), equip.EquipNum);
                            // 开始进行作业
                            equip.HandleTray2 = equip.A_Tray2;
                        }
                        else
                        {
                            // 写入报错
                            equip.Message = datas.Message;
                            await _processDataService.WriteCeb("W_A_I_CHECK2", "2", equip.EquipNum);
                        }
                        await _processDataService.WriteCeb("W_A_I_CHECK2", "1", equip.EquipNum);
                    }
                    else
                    {
                        equip.Message = validate1.Message;
                        await _processDataService.WriteCeb("W_A_I_CHECK2", "2", equip.EquipNum);
                    }
                    equip.IsValidateTray2 = true;
                }
                else if (equip.A_I_Check2 == 0) equip.IsValidateTray2 = false;

              
            }
            else
            {
                if (equip.A_O_Check2 == 1 && equip.W_A_O_Check2 == 0)
                {


                    // 调用方法通知 两个tray会判断
                    var result = await _processDataService.CebWorkDoneInform(new IotContract.Dtos.Remotes.Request.FmsTrayRequest { EmptyTray = equip.A_Tray4, Tray = equip.A_Tray2, EquipNum = equip.EquipNum });

                    if (result.Success)
                    {
                        await _processDataService.WriteCeb("W_A_O_CHECK2", "1", equip.EquipNum);
                    }
                    else
                    {
                        await _processDataService.WriteCeb("W_A_O_CHECK2", "2", equip.EquipNum);
                    }

                   

                    equip.HandleTray2 = string.Empty;

                }
                else if (equip.A_O_Check2 == 0) equip.IsValidateTray1 = false;


            }

          


        });
        return true;
    }

    public async Task<bool> ProcessOrder()
    {
        return true;
    }

    public async Task<bool> ProcessWarn()
    {
        return true;
    }

    public bool Stop()
    {
        return true;
    }
}
